//
//  DDQuestionAnswerOptionSetViewController.m
//  dingdang
//
//  Created by Chen Jing on 15-7-6.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDQuestionAnswerOptionSetViewController.h"
#import "DDQuestionAnswerOptionElementView.h"
#import "PECropViewController.h"
#import "DDQuestionAnswerSetElementBodyViewController.h"
#import "DDNetWorkAPIClient.h"
#import "UIImageView+WebCache.h"
#import "MWPhotoBrowser.h"
#import "MWPhoto.h"


@interface DDQuestionAnswerOptionSetViewController ()<DDQuestionAnswerOptionElementViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PECropViewControllerDelegate,DDQuestionAnswerSetElementBodyViewControllerDelegate,UIActionSheetDelegate,MWPhotoBrowserDelegate>{
    NSMutableArray * array_answers;
    NSMutableArray * array_views;
    NSArray * indexArray;
    NSMutableArray * array_btns;
    UIImage * paramImage_process;
    NSString * paramImageString_process;

    NSMutableDictionary * currentTempMutiDic;
    NSString * keyParamDic_body;
    NSString * keyParamDic_image;
    
    BOOL isFromTap_hotoBrowser;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView_main;
@property (weak, nonatomic) IBOutlet UIView *contentOfTopView;
@property (weak, nonatomic) IBOutlet UIView *contentOfChooseAnswerView;
@property (weak, nonatomic) IBOutlet UIView *contentOfExplainView;
@property (weak, nonatomic) IBOutlet UIButton *btn_A;
@property (weak, nonatomic) IBOutlet UIButton *btn_B;
@property (weak, nonatomic) IBOutlet UIButton *btn_C;
@property (weak, nonatomic) IBOutlet UIButton *btn_D;
@property (weak, nonatomic) IBOutlet UIButton *btn_E;
@property (weak, nonatomic) IBOutlet UIButton *btn_F;
@property (weak, nonatomic) IBOutlet UIImageView *imageView_answerImage;
@property (weak, nonatomic) IBOutlet UITextView *textView_answer;
@end

@implementation DDQuestionAnswerOptionSetViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSMutableDictionary *)assemblyDic{
    NSMutableDictionary * muDic = [NSMutableDictionary dictionary];
    NSMutableArray * optionArray = [NSMutableArray array];

    for (int i = 0; i < array_answers.count; i++) {
        NSMutableDictionary * tempDic = array_answers[i];

        NSMutableDictionary * optionElementDic = [NSMutableDictionary dictionary];

        NSMutableArray * elementArray = [NSMutableArray array];
        NSString * bodyString = [tempDic objectForKey:keyParamDic_body];
        if (bodyString) {
            [elementArray addObject:@{
                                      @"type" : @"TEXT",
                                      @"text" : bodyString,
                                      }];
        }
        NSString * imageURLString = [tempDic objectForKey:keyParamDic_image];
        if (imageURLString) {
            [elementArray addObject:@{
                                      @"type" : @"IMAGE",
                                      @"url" : imageURLString,
                                      }];
        }

        UIButton * tempBtn = array_btns[i];

        [optionElementDic setObject:elementArray forKey:@"content"];
        [optionElementDic setObject:indexArray[i] forKey:@"label"];
//        [optionElementDic setObject:[NSNumber numberWithBool:tempBtn.selected] forKey:@"currect"];
        if (tempBtn.selected == YES) {
            [optionElementDic setObject:@"true" forKey:@"currect"];
        }else{
            [optionElementDic setObject:@"false" forKey:@"currect"];
        }



        [optionArray addObject:optionElementDic];

    }
    [muDic setObject:optionArray forKey:@"options"];


    NSMutableArray * explanationArray = [NSMutableArray array];
    if (self.textView_answer.text.length > 0) {
        [explanationArray addObject:@{
                                      @"type" : @"TEXT",
                                      @"text" : self.textView_answer.text,
                                      }];
    }
    if (paramImageString_process) {
        [explanationArray addObject:@{
                                      @"type" : @"IMAGE",
                                      @"url" : paramImageString_process,
                                      }];
    }

    [muDic setObject:explanationArray forKey:@"explanation"];

    return muDic;
}

-(void)createUI{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addNavigatorTitle:NSLocalizedString(@"设置选项/答案", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];

    [self AddLeftBtnAction:@"" normal:@"top_返回" selected:@"top_返回" action:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];

    [self AddRightBtnAction:@"完成" normal:@"" selected:@"" action:^{
        if (self.delegate && [self.delegate respondsToSelector:@selector(DDQuestionAnswerOptionSetFinish:)]) {
            NSMutableDictionary * resultDic = [self assemblyDic];
            [self.delegate performSelector:@selector(DDQuestionAnswerOptionSetFinish:) withObject:resultDic];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];

    self.textView_answer.layer.cornerRadius = 5;
    self.textView_answer.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.textView_answer.layer.borderWidth = .5;
    self.textView_answer.layer.masksToBounds = YES;

    keyParamDic_body = @"keyParamDic_body";
    keyParamDic_image = @"keyParamDic_image";
    
}

-(void)createData{
    array_answers = [NSMutableArray array];
    array_btns = [NSMutableArray arrayWithArray:@[self.btn_A,
                                                  self.btn_B,
                                                  self.btn_C,
                                                  self.btn_D,
                                                  self.btn_E,
                                                  self.btn_F]];

    if (self.info_questionType == DDType_question_questionType_PanDuanTi) {
        for (int i = 0; i < 2; i++) {
            NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
            
            if (self.info_oldData) {
                NSArray * tempArray = self.info_oldData[@"options"];
                if (tempArray.count > 0 && i < tempArray.count) {
                    NSDictionary * optionsDic = tempArray[i];
                    NSArray * contentArray = optionsDic[@"content"];
                    for (int j = 0; j < contentArray.count; j++) {
                        NSDictionary * bodyDic = contentArray[j];
                        if ([bodyDic[@"type"] isEqualToString:@"TEXT"]) {
                            if (i == 0) {
                                [tempDic setObject:@"正确" forKey:keyParamDic_body];
                            }else{
                                [tempDic setObject:@"错误" forKey:keyParamDic_body];
                            }
                        }else if ([bodyDic[@"type"] isEqualToString:@"IMAGE"]){
                            [tempDic setObject:@"url" forKey:keyParamDic_image];
                        }
                    }
                    
                    if ([optionsDic[@"currect"] isEqualToString:@"true"]) {
                        UIButton * tempBtn = array_btns[i];
                        tempBtn.selected = YES;
                    }

                }
            }else{
                if (i == 0) {
                    [tempDic setObject:@"正确" forKey:keyParamDic_body];
                    [tempDic setObject:@"true" forKey:@"currect"];
                    UIButton * tempBtn = array_btns[i];
                    tempBtn.selected = YES;
                }else{
                    [tempDic setObject:@"错误" forKey:keyParamDic_body];
                    [tempDic setObject:@"false" forKey:@"currect"];

                }
            }
            
            [array_answers addObject:tempDic];
        }
    }else{
        for (int i = 0; i < 4; i++) {
            NSMutableDictionary * tempDic = [NSMutableDictionary dictionary];
            if (self.info_oldData) {
                NSArray * tempArray = self.info_oldData[@"options"];
                if (tempArray.count > 0 && i < tempArray.count) {
                    NSDictionary * optionsDic = tempArray[i];
                    NSArray * contentArray = optionsDic[@"content"];
                    for (int j = 0; j < contentArray.count; j++) {
                        
                        NSDictionary * bodyDic = contentArray[j];
                        if ([bodyDic[@"type"] isEqualToString:@"TEXT"]) {
                            [tempDic setObject:bodyDic[@"text"] forKey:keyParamDic_body];
                        }else if ([bodyDic[@"type"] isEqualToString:@"IMAGE"]){
                            [tempDic setObject:@"url" forKey:keyParamDic_image];
                        }

                    
                    }
                    if ([optionsDic[@"currect"] isEqualToString:@"true"]) {
                        UIButton * tempBtn = array_btns[i];
                        tempBtn.selected = YES;
                    }
                }
            }else{
                if (i == 0) {
                    [tempDic setObject:@"true" forKey:@"currect"];
                    UIButton * tempBtn = array_btns[i];
                    tempBtn.selected = YES;
                }
            }
            [array_answers addObject:tempDic];
        }
    }
    
    /*
    if (self.textView_answer.text.length > 0) {
        [explanationArray addObject:@{
                                      @"type" : @"TEXT",
                                      @"text" : self.textView_answer.text,
                                      }];
    }
    if (paramImageString_process) {
        [explanationArray addObject:@{
                                      @"type" : @"IMAGE",
                                      @"url" : paramImageString_process,
                                      }];
    }
     */

    
    if (self.info_oldData) {
        NSArray * explanationArray = self.info_oldData[@"explanation"];
        if (explanationArray.count > 0) {
            for (int i = 0; i < explanationArray.count; i++) {
                NSDictionary * tempExDic = explanationArray[i];
                if ([tempExDic[@"type"] isEqualToString:@"TEXT"]) {
                    self.textView_answer.text = tempExDic[@"text"];
                }else if ([tempExDic[@"type"] isEqualToString:@"IMAGE"]){
                    paramImageString_process = tempExDic[@"url"];
                    [self.imageView_answerImage sd_setImageWithURL:[NSURL URLWithString:paramImageString_process] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                        paramImage_process = image;
                    }];
                }
            }
        }
    }
    

    array_views = [NSMutableArray array];
    indexArray = @[@"A",@"B",@"C",@"D",@"E",@"F"];

    [self resetAnswerViews];

}

-(void)resetAnswerViews{
//    [array_views makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (UIView * myTempView in array_views) {
        [myTempView removeFromSuperview];
    }
    [array_views removeAllObjects];

    for (UIButton * tempBtn in array_btns) {
        tempBtn.hidden = YES;
    }

    for (int i = 0; i < array_answers.count; i++) {

        UIButton * tempBtn = array_btns[i];
        tempBtn.hidden = NO;

        DDQuestionAnswerOptionElementView * tempView = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([DDQuestionAnswerOptionElementView class]) owner:nil options:nil]firstObject];
        tempView.label_index.text = indexArray[i];
        NSMutableDictionary * tempDic = array_answers[i];
        if ([tempDic objectForKey:keyParamDic_body]) {
            tempView.label_answerBody.text = [tempDic objectForKey:keyParamDic_body];
        }
        
        if ([tempDic objectForKey:keyParamDic_image]) {
            [tempView.imageView_add setImage:[UIImage imageNamed:@"1111"]];
        }else{
            [tempView.imageView_add setImage:[UIImage imageNamed:@"发问-设置答案-图片图标"] ];
        }
        
        if (self.info_questionType == DDType_question_questionType_PanDuanTi) {
            tempView.btn_minus.hidden = YES;
            tempView.btn_plus.hidden = YES;
            tempView.btn_setImage.hidden = YES;
            tempView.contentOfImage.hidden = YES;
            tempView.btn_editBody.enabled = NO;
        }
        
        tempView.delegate = self;
        tempView.frame = CGRectMake(0,
                                    CGRectGetHeight(tempView.frame) * i,
                                    CGRectGetWidth(self.contentOfTopView.frame),
                                    CGRectGetHeight(tempView.frame));
        [self.contentOfTopView addSubview:tempView];
        [array_views addObject:tempView];
    }
    self.contentOfTopView.frame = CGRectMake(0, 0, CGRectGetWidth(self.contentOfTopView.frame),array_views.count * 40);
    self.contentOfChooseAnswerView.frame = CGRectMake(0,
                                                      CGRectGetHeight(self.contentOfTopView.frame) + 8,
                                                      CGRectGetWidth(self.contentOfChooseAnswerView.frame),
                                                      CGRectGetHeight(self.contentOfChooseAnswerView.frame));


    if (paramImageString_process) {
        [self.imageView_answerImage sd_setImageWithURL:[NSURL URLWithString:paramImageString_process]];
        self.contentOfExplainView.frame = CGRectMake(0,
                                                     CGRectGetMinY(self.contentOfChooseAnswerView.frame) + CGRectGetHeight(self.contentOfChooseAnswerView.frame) + 8,
                                                     CGRectGetWidth(self.contentOfExplainView.frame),
                                                     290 + 170);
    }else{
        self.contentOfExplainView.frame = CGRectMake(0,
                                                     CGRectGetMinY(self.contentOfChooseAnswerView.frame) + CGRectGetHeight(self.contentOfChooseAnswerView.frame) + 8,
                                                     CGRectGetWidth(self.contentOfExplainView.frame),
                                                     200);
    }
    self.scrollView_main.contentSize = CGSizeMake(CGRectGetWidth([[UIScreen mainScreen] bounds]),
                                                  CGRectGetMinY(self.contentOfExplainView.frame) + CGRectGetHeight(self.contentOfExplainView.frame) + 20);

}



- (IBAction)openCameraBtnClick:(id)sender {
    currentTempMutiDic = nil;
    [self openCamera];
}
- (IBAction)openPhotoLibBtnClick:(id)sender {
    currentTempMutiDic = nil;
    [self openPhotoLib];
}

- (IBAction)btnRightAnswerTouch:(UIButton *)sender {
    if (self.info_questionType == DDType_question_questionType_DanXuanTi) {
        for (UIButton * tempBtn in array_btns) {
            tempBtn.selected = NO;
        }
        sender.selected = YES;
    }else{
        sender.selected = !sender.selected;
    }
}

- (IBAction)tapOnImageView:(id)sender {
    MWPhotoBrowser * browser = [[MWPhotoBrowser alloc]initWithDelegate:self];
    browser.displayActionButton = NO;
    isFromTap_hotoBrowser = YES;
    [self.navigationController pushViewController:browser animated:YES];
}

#pragma mark - DDQuestionAnswerOptionElementViewDelegate

-(void)element_EditAnswer:(DDQuestionAnswerOptionElementView *)elementView{
    
    DDQuestionAnswerSetElementBodyViewController * setBodyVC = [[DDQuestionAnswerSetElementBodyViewController alloc]init];
    setBodyVC.delegate = self;
    currentTempMutiDic = [array_answers objectAtIndex:[array_views indexOfObject:elementView]];
    setBodyVC.info_oldString = [currentTempMutiDic objectForKey:keyParamDic_body];
    [self.navigationController pushViewController:setBodyVC animated:YES];
    
    
}
-(void)element_ClickImage:(DDQuestionAnswerOptionElementView *)elementView{
    currentTempMutiDic = [array_answers objectAtIndex:[array_views indexOfObject:elementView]];
    
    if ([[currentTempMutiDic objectForKey:keyParamDic_image] length] > 0) {
        MWPhotoBrowser * browser = [[MWPhotoBrowser alloc]initWithDelegate:self];
        browser.displayActionButton = NO;
        isFromTap_hotoBrowser = NO;
        [self.navigationController pushViewController:browser animated:YES];
    }else{
    
        UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
        [actionSheet showInView:self.view];
    }
}
-(void)element_Minus:(DDQuestionAnswerOptionElementView *)elementView{
    if (array_answers.count > 1) {
        [array_answers removeObjectAtIndex:[array_views indexOfObject:elementView]];
        [self resetAnswerViews];
    }else{
        [self delayHUD:@"至少要设置一个选项"];
    }

}
-(void)element_Plus:(DDQuestionAnswerOptionElementView *)elementView{
    NSInteger index = [array_views indexOfObject:elementView];
    index++;
    if (array_answers.count == indexArray.count) {
        [self delayHUD:@"选项不能超过6个"];
        return;
    }
    if (index < indexArray.count && array_answers.count < indexArray.count) {
        NSMutableDictionary * tempMuDic = [NSMutableDictionary dictionary];
        [array_answers insertObject:tempMuDic atIndex:index];
        [self resetAnswerViews];
    }
}
-(void)element_deleteImage:(DDQuestionAnswerOptionElementView *)elementView{
    
    NSInteger index = [array_views indexOfObject:elementView];
    NSMutableDictionary * tempDic = [array_answers objectAtIndex:index];
    [tempDic removeObjectForKey:keyParamDic_image];
    [self resetAnswerViews];
}


-(void)openCamera{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

-(void)openPhotoLib{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}


- (void)openEditor
{
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = paramImage_process;

    UIImage *image = paramImage_process;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat length = MIN(width, height);
    controller.imageCropRect = CGRectMake((width - length) / 2,
                                          (height - length) / 2,
                                          length,
                                          length);

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];

    [self presentViewController:navigationController animated:YES completion:nil];
}

#pragma mark - pickerImage Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    UIImage *image = info[UIImagePickerControllerOriginalImage];
    paramImage_process = image;
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openEditor];
    }];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -  PECropViewControllerDelegate
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{

    DDNetWorkAPIClient * networkClient = [[DDNetWorkAPIClient alloc]init];
    NSMutableDictionary * param = [NSMutableDictionary dictionary];

    NSData * imageData = UIImageJPEGRepresentation(croppedImage, 0.1);
    NSString * imageString = [imageData base64EncodedStringWithOptions:0];

    [param setObject:imageString forKey:@"data"];
    [param setObject:@"jpg" forKey:@"extName"];

    [self showHUD:@"正在处理图片"];
    if (currentTempMutiDic) {
        [networkClient uploadImage:param completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            if ([[object objectForKey:@"code"] integerValue] == 0) {
                if ([object objectForKey:@"data"]) {
                    [currentTempMutiDic setObject:[object objectForKey:@"data"] forKey:keyParamDic_image];
                }
            }
            [self hideHUD];
        }];

    }else{
        [networkClient uploadImage:param completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
            if ([[object objectForKey:@"code"] integerValue] == 0) {
                if ([object objectForKey:@"data"]) {
                    paramImageString_process = [object objectForKey:@"data"];
                    [self.imageView_answerImage sd_setImageWithURL:[NSURL URLWithString:paramImageString_process]];
                    [self resetAnswerViews];
                }
            }
            [self hideHUD];
        }];

    }
    [controller dismissViewControllerAnimated:YES completion:^{
        [self resetAnswerViews];
    }];
    

    //    paramImage_process = croppedImage;
    //    [self.tableView reloadData];

}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - DDQuestionAnswerSetElementBodyViewControllerDelegate
-(void)DDQuestionAnswerSetElementBodyViewControllerEditFinish:(NSString *)content{
    if (currentTempMutiDic) {
        [currentTempMutiDic setObject:content forKey:keyParamDic_body];
        [self resetAnswerViews];
    }
}

#pragma mark - actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){
        [self openCamera];
    }else if (buttonIndex == 1){
        [self openPhotoLib];
    }
}


- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
    return 1;
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    
    if (isFromTap_hotoBrowser == YES) {
        MWPhoto * photo = [[MWPhoto alloc]initWithURL:[NSURL URLWithString:paramImageString_process]];
        return photo;
    }else{
        MWPhoto * photo = [[MWPhoto alloc]initWithURL:[NSURL URLWithString:[currentTempMutiDic objectForKey:keyParamDic_image]]];
        return photo;
    }
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
